﻿using IPR_StudyMeetingMrgSys.Common;
using IPR_StudyMeetingMrgSys.Enums;
using IPR_StudyMeetingMrgSys.Extension;
using IPR_StudyMeetingMrgSys.Models;
using log4net;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Web;
using System.Web.Http;

namespace IPR_StudyMeetingMrgSys.Controllers
{
    /// <summary>
    /// 试题操作控制器
    /// </summary>
    public class ExamQuestionsController : ApiController
    {
        ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        public IHttpActionResult Get(int EQID)
        {
            ResultMsg resultMsg = new ResultMsg();
            resultMsg.StatusCode = (int)StatusCodeEnum.Success;
            try
            {
                Model.ExamQuestions model = new BLL.ExamQuestions().GetModel(EQID);
                if (model != null)
                {
                    resultMsg.Info = StatusCodeEnum.Success.GetEnumText();
                    resultMsg.Data = model;
                    resultMsg.Count = 1;
                }
                else
                {
                    resultMsg.Info = "未获取到相应数据";
                }
            }
            catch (Exception ex)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                resultMsg.Data = ex.Message;
                log.Error(ex);
            }
            return Json(resultMsg);
        }

        /// <summary>
        /// 试题的增加
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [Route("api/ExamQuestions/Add")]
        [HttpPost]
        public IHttpActionResult Add(Model.ExamQuestions model)
        {
            ResultMsg resultMsg = new ResultMsg();
            resultMsg.StatusCode = (int)StatusCodeEnum.Success;
            try
            {
                model.EQAddDateTime = DateTime.Now;
                model.EQIsAutoMark = 1;
                Model.T_UserInfo loginuser = LoginUser.UserInfo;
                model.EQDesignEmpID = loginuser.UserID;
                model.EQDesignEmpName = loginuser.UserName;
                model.EQAddEmpID = loginuser.UserID;
                model.EQAddEmpName = loginuser.UserName;

                log.Info(JsonConvert.SerializeObject(model));

                BLL.ExamQuestions _ExamQuestions = new BLL.ExamQuestions();
                if (new BLL.ExamQuestions().Add(model) > 0)
                {
                    resultMsg.Info = "增加成功";
                    resultMsg.Count = 1;
                }
                else
                {
                    resultMsg.Info = "增加失败";
                }

            }
            catch (Exception ex)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                resultMsg.Data = ex.Message;
                log.Error(ex);
            }
            return Json(resultMsg);
        }

        /// <summary>
        /// 试题查询
        /// </summary>
        /// <param name="swhere"></param>
        /// <param name="startindex"></param>
        /// <param name="endindex"></param>
        /// <returns></returns>
        //[HttpGet]
        //[Route("api/ExamQuestions/Search")]
        //public IHttpActionResult Search(string swhere, int startindex, int endindex)
        //{
        //    ResultMsg resultMsg = new ResultMsg();
        //    try
        //    {
        //        bool blExist = false;
        //        if (swhere != null)
        //            swhere = "EQID=" + swhere;
        //        else
        //            swhere = "1=1";
        //        DataSet dsSearch = new BLL.ExamQuestions().GetListByPage(swhere, "EQID", startindex, endindex);
        //        if (dsSearch != null)
        //            if (dsSearch.Tables.Count > 0)
        //                if (dsSearch.Tables[0].Rows.Count > 0)
        //                {
        //                    //返回token信息
        //                    resultMsg.StatusCode = (int)StatusCodeEnum.Success;
        //                    resultMsg.Info = StatusCodeEnum.Success.GetEnumText();
        //                    resultMsg.Data = dsSearch.Tables[0];
        //                    blExist = true;
        //                }
        //        if (!blExist)
        //        {
        //            //返回token信息
        //            resultMsg.StatusCode = (int)StatusCodeEnum.Error;
        //            resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
        //            resultMsg.Data = "试题不存在！";
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        resultMsg.StatusCode = (int)StatusCodeEnum.Error;
        //        resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
        //        resultMsg.Data = ex.Message;
        //        log.Error(ex);
        //    }
        //    return Json(resultMsg);
        //}

        /// <summary>
        /// 试题编辑
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/ExamQuestions/Edit")]
        public IHttpActionResult Edit(Model.ExamQuestions model)
        {
            log.Info(JsonConvert.SerializeObject(model));

            ResultMsg resultMsg = new ResultMsg();
            resultMsg.StatusCode = (int)StatusCodeEnum.Success;
            try
            {
                model.EQIsAutoMark = 1;
                if (new BLL.ExamQuestions().Update(model))
                {
                    resultMsg.Info = "编辑成功";
                    resultMsg.Count = 1;
                }
                else
                {
                    resultMsg.Info = "编辑失败";
                }
            }
            catch (Exception ex)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                resultMsg.Data = ex.Message;
                log.Error(ex);
            }
            return Json(resultMsg);
        }
        /// <summary>
        /// 试题删除
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/ExamQuestions/Del")]
        public IHttpActionResult Del(Model.ExamQuestions model)
        {
            log.Info(JsonConvert.SerializeObject(model.EQID));

            ResultMsg resultMsg = new ResultMsg();
            resultMsg.StatusCode = (int)StatusCodeEnum.Success;
            try
            {
                if (new BLL.ExamQuestions().Delete(model.EQID))
                {
                    resultMsg.Info = "删除成功";
                    resultMsg.Count = 1;
                }
                else
                {
                    resultMsg.Info = "删除失败";
                }
            }
            catch (Exception ex)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                resultMsg.Data = ex.Message;
                log.Error(ex);
            }
            return Json(resultMsg);
        }

        /// <summary>
        /// 试题信息分页查找
        /// </summary>
        /// <param name="swhere">查询条件</param>
        /// <param name="page">页索引</param>
        /// <param name="limit">页大小</param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/ExamQuestions/SelListPage")]
        public IHttpActionResult SelListPage(string swhere, int page, int limit)
        {
            log.Info(JsonConvert.SerializeObject(swhere + "#1"));
            ResultMsg resultMsg = new ResultMsg();
            resultMsg.StatusCode = (int)StatusCodeEnum.Success;
            try
            {
                int startindex = (page - 1) * limit + 1;
                int endindex = page * limit;

                if (swhere != "")
                {
                    swhere = " 1=1 " + swhere;
                }
                else
                { swhere = " 1=1 "; }
                int rowCount = 0;
                bool blExist = false;
                DataSet dsSearch = new IPR_StudyMeetingMrgSys.BLL.ExamQuestions().GetListByPage(swhere, "EQID", startindex, endindex, out rowCount);
                if (dsSearch != null)
                    if (dsSearch.Tables.Count > 0)
                        if (dsSearch.Tables[0].Rows.Count > 0)
                        {
                            resultMsg.Info = StatusCodeEnum.Success.GetEnumText();
                            resultMsg.Count = rowCount;
                            resultMsg.Data = dsSearch.Tables[0];
                            blExist = true;
                        }
                if (!blExist)
                {
                    resultMsg.Info = "未获取到相应数据";
                }
            }
            catch (Exception ex)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                resultMsg.Data = ex.Message;
                log.Error(ex);
            }
            return Json(resultMsg);
        }
        /// <summary>
        /// 根据eqid得到一个model
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/ExamQuestions/getmodel")]
        public IHttpActionResult getmodel(Model.ExamQuestions model)
        {
            ResultMsg resultMsg = new ResultMsg();
            resultMsg.StatusCode = (int)StatusCodeEnum.Success;
            try
            {
                DataSet dsSearch = new BLL.ExamQuestions().GetListView(" and EQID=" + model.EQID);
                if (dsSearch != null && dsSearch.Tables.Count > 0)

                    if (dsSearch.Tables[0].Rows.Count > 0)
                    {
                        resultMsg.Info = StatusCodeEnum.Success.GetEnumText();
                        resultMsg.Data = dsSearch.Tables[0];
                        resultMsg.Count = 1;
                    }
                    else
                    {
                        resultMsg.Info = "未获取到相应数据";
                    }
            }
            catch (Exception ex)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                resultMsg.Data = ex.Message;
                log.Error(ex);
            }
            return Json(resultMsg);
        }

        /// <summary>
        /// 试题查询 gaoqihang
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("api/ExamQuestions/SelListForSelQuestion")]
        public IHttpActionResult SelListForSelQuestion()
        {
            ResultMsg resultMsg = new ResultMsg();
            resultMsg.StatusCode = (int)StatusCodeEnum.Success;
            try
            {
                DataTable dt = new BLL.ExamQuestions().GetListForSelQuestion("").Tables[0];

                resultMsg.StatusCode = (int)StatusCodeEnum.Success;
                resultMsg.Info = dt.Rows.Count > 0 ? StatusCodeEnum.Success.GetEnumText() : "未获取到相应数据";
                resultMsg.Data = dt;
                resultMsg.Count = dt.Rows.Count;
            }
            catch (Exception ex)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                resultMsg.Data = ex.Message;
                log.Error(ex);
            }
            return Json(resultMsg);
        }

        #region 试题上传
        [HttpPost]
        [Route("api/ExamQuestions/Upload")]
        public IHttpActionResult FileUpload()
        {
            ResultMsg resultMsg = new ResultMsg();
            resultMsg.StatusCode = (int)StatusCodeEnum.Success;
            try
            {
                int EQSubject = Convert.ToInt32(string.IsNullOrWhiteSpace(HttpContext.Current.Request["EQSubject"]) ? "0" : HttpContext.Current.Request["EQSubject"]);
                var file = HttpContext.Current.Request.Files.Count > 0 ? HttpContext.Current.Request.Files[0] : null;
                if (file != null && file.ContentLength > 0 && EQSubject != 0)
                {
                    string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + Path.GetFileName(file.FileName);
                    string path = HttpContext.Current.Server.MapPath("~/UploadTemp");
                    Directory.CreateDirectory(path);
                    file.SaveAs(Path.Combine(path, fileName));
                    ExcelHelper excelHelper = new ExcelHelper(Path.Combine(path, fileName));
                    DataTable dataTable = excelHelper.ExcelToDataTable(0, 0);
                    if (dataTable.Rows.Count == 0)
                    {
                        resultMsg.Info = "未获取到上传数据";
                        return Json(resultMsg);
                    }
                    List <Model.ExamQuestions> modellist = new List<Model.ExamQuestions>();
                    Model.T_UserInfo employee = LoginUser.UserInfo;
                    foreach (DataRow dr in dataTable.Rows)
                    {
                        Model.ExamQuestions examQuestions = new Model.ExamQuestions()
                        {
                            EQIntegral = 0,
                            EQUseCount = 0,
                            EQIsAutoMark = 0,
                            EQDesignEmpID = employee.UserID,
                            EQDesignEmpName = employee.UserName,
                            EQAddEmpID = employee.UserID,
                            EQAddEmpName = employee.UserName,
                            EQAddDateTime = DateTime.Now
                        };
                        examQuestions.ETID = GetUploadETID(dr[0].ToString());
                        examQuestions.EQSubject = EQSubject;
                        examQuestions.EQContent = dr[1].ToString();
                        examQuestions.EQAnswer = dr[2].ToString();
                        examQuestions.EQScore = Convert.ToInt32(dr[3]);
                        modellist.Add(examQuestions);
                    }
                    new BLL.ExamQuestions().AddList(modellist);
                    resultMsg.Info = "上传成功";
                    resultMsg.Count = dataTable.Rows.Count;
                }
                else
                {
                    resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                    resultMsg.Info = "知识点类型不对或上传的文件为空";
                }
            }
            catch (Exception ex)
            {
                resultMsg.StatusCode = (int)StatusCodeEnum.Error;
                resultMsg.Info = StatusCodeEnum.Error.GetEnumText();
                resultMsg.Data = ex.Message;
                log.Error(ex);
            }
            return Json(resultMsg);
        }
        /// <summary>
        /// 获取上传数据的试题类型
        /// </summary>
        /// <param name="ETName">试题类型名称</param>
        /// <returns></returns>
        private int GetUploadETID(string ETName)
        {
            switch (ETName)
            {
                case "选择":
                    return 1;
                case "判断":
                    return 2;
                case "填空":
                    return 3;
                case "简答":
                    return 4;
                case "综合":
                    return 5;
                default:
                    return 0;
            }
        }
        #endregion
    }
}
                    

